package com.tjb.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;

public class FastJsonUtil {
    /**
     * 获取json格式字符串
     * @param object
     * @return
     */
    public static String getJson(Object object){
        try {
            return new ObjectMapper().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("对象转json异常",e);
        }
    }

    /**
     * Json转对象
     * @param json
     * @param c
     * @return
     */
    public static Object getObject(String json,Class<?> c){
        try {
            return new ObjectMapper().readValue(json,c);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("Json转对象异常",e);
        }
    }

    /**
     * json设置时间格式
     * @param obj
     * @param dateFormat
     * @return
     */
    public static String setFormat(Object obj,String dateFormat){
        try {
            return new ObjectMapper().setDateFormat(new SimpleDateFormat(dateFormat)).writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("返回Json自定义时间格式异常",e);
        }
    }
}
